<?php
/**
 * DB
 * 
 * 作者:  姚刚 (yaogang@the9sense.com)
 * 创建时间: 2011-03-06 04:08:53
 * 修改记录: 
 * 
 * $Id: DB.php 18 2011-04-17 12:50:07Z coosuu $
 */

class DB {

    private static $_conns = array();

    private $_dbh;

    /**
     * db 构造函数
     *
     * @param string $dsn
     * @param string $user
     * @param string $password
     */
    private function __construct($dsn, $user, $password) {

        $attr = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
        try {
            $this->_dbh = new PDO($dsn, $user, $password, $attr);
            $this->_dbh->exec("SET NAMES 'utf8'");
        }catch (PDOException $e){
            throw new DB_Exception("can't connect to mysql server :" . $e->getMessage());
        }
    }

    /**
     * 获取数据库连接类
     *
     * @param string $dsn
     * @param string $user
     * @param string $password
     * @return DB 实例
     */
    public static function connect($dsn, $user, $password) {

        if (!array_key_exists($dsn, self::$_conns)){
            self::$_conns[$dsn] = new DB($dsn, $user, $password);
        }

        return self::$_conns[$dsn];
    }

    /**
     * 开启事物
     */
    public function begin() {

        $this->_dbh->beginTransaction();
    }

    /**
     * 提交事务
     */
    public function commit() {

        $this->_dbh->commit();
    }

    /**
     * 回滚事务
     */
    public function rollBack() {

        $this->_dbh->rollBack();
    }

    /**
     * 取得记录的第一行
     *
     * @param sql string $query
     * @param array $params
     */
    public function getRow($query, $params = array()) {

        $stmt = $this->_dbh->prepare($query);
        $stmt->execute($params);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row;
    }

    /**
     * 取得所有的记录
     *
     * @param sql string $query
     * @param array $params
     * @return array
     */
    public function getAll($query, $params = array()) {

        $stmt = $this->_dbh->prepare($query);
        $stmt->execute($params);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $rows;
    }

    /**
     * 获取记录的第一行第一列
     *
     * @param string sql $query
     * @param array $params
     */
    public function getOne($query, $params = array()) {

        $stmt = $this->_dbh->prepare($query);
        $result = $stmt->execute($params);
        if ($result) {
            $row = $stmt->fetchColumn();
        }
        return $row ;
    }

    /**
     * 执行sql 语句
     *
     * @param sqlstring $query
     * @param array $params
     * @return 更新的记录的条数
     */
    public function exec($query, $params = array()) {

        $stmt = $this->_dbh->prepare($query);
        return $stmt->execute($params);
    }

    /**
     * getLastInsertId 
     * 
     * @return void
     */
    public function getLastInsertId() {

        return $this->_dbh->lastInsertId();
    }
}
